//
//  RoundedRectangleView.m
//  yuikemall
//
//  Created by Gang.Wang on 12-6-29.
//  Copyright (c) 2012年 yuike. All rights reserved.
//

#import "RoundedRectangleView.h"
#import "header.h"

@interface RoundedRectangleView()
{
    CGContextRef mCtx_;
}

@property (nonatomic, assign) CGContextRef mCtx;


- (void) privateInit;

- (void) drawRectangle;

@end

@implementation RoundedRectangleView

@synthesize mCtx = mCtx_;

- (void)dealloc
{
    [super dealloc];
}


#pragma mark - Public Method

- (id) init
{
    self = [super init];
    if (self) {
        [self privateInit];
    }
    
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self privateInit];
    }
    return self;
}

- (CGContextRef) mCtx
{
    if (!mCtx_) {
        mCtx_ = UIGraphicsGetCurrentContext();
    }
    
    return mCtx_;
}




 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
     [self drawRectangle];
 }
 

#pragma mark - Private Method
- (void) privateInit
{
    if (self.bInited) {
        return;
    }
    
    
    [self reAdjustLayout];
    self.bInited = TRUE;
}


- (void) drawRectangle
{
    
    CGFloat flag = self.width > self.height ? self.width / 10 : self.height / 10; 

    CGFloat radius = flag;
    
    CGRect rrect = CGRectMake(flag, 
                              flag, 
                              self.width - flag - flag, 
                              self.height - flag - flag);
    
    CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect); 
    CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
        
  
    CGContextScaleCTM(self.mCtx, 1.0, -1.0);
    CGContextTranslateCTM(self.mCtx, 0, -self.height);
        
    CGContextBeginPath(self.mCtx);
    CGContextMoveToPoint(self.mCtx, minx, midy); 
    CGContextAddArcToPoint(self.mCtx, minx, miny, midx, miny, radius); 
    CGContextAddArcToPoint(self.mCtx, maxx, miny, maxx, midy, radius); 
    CGContextAddArcToPoint(self.mCtx, maxx, maxy, midx, maxy, radius); 
    CGContextAddArcToPoint(self.mCtx, minx, maxy, minx, midy, radius); 

    CGContextClosePath(self.mCtx); 
    CGContextClip(self.mCtx);
//    CGContextRestoreGState(self.mCtx);
    CGContextDrawImage(self.mCtx, self.bounds, self.image.CGImage);
 
    return;
}

@end
